package casia.isiteam.springbootshiro.controller.event;

import casia.isiteam.springbootshiro.model.po.common.Institution;
import casia.isiteam.springbootshiro.model.po.common.UserInfo;
import casia.isiteam.springbootshiro.properties.other.ConfigurationItem;
import casia.isiteam.springbootshiro.properties.other.HttpState;
import casia.isiteam.springbootshiro.properties.result.HttpResult;
import casia.isiteam.springbootshiro.service.event.EventService;
import casia.isiteam.springbootshiro.service.user.UserInfoService;
import casia.isiteam.springbootshiro.util.TimeUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * Author wzy
 * Date 2018/1/15 15:57
 */
@RestController
public class Home {
    private final static Logger logger = LoggerFactory.getLogger(Home.class);

    @Autowired
    private EventService eventService;
    @Autowired
    private UserInfoService userInfo;
//    @Autowired
//    private JavaMailSender mailSender;

    @ApiOperation(value="创建单位", notes="创建单位")
    @RequestMapping(value = "addInstitution",method={ RequestMethod.POST } )
    public Object addInstitution( Institution institution ) throws Exception{
        Institution rs_institution1 = eventService.saveInstitution(institution);
        return HttpResult.sucess(rs_institution1);
    }
    @ApiOperation(value="根据单位ID查询部门", notes="根据单位ID查询部门")
    @RequestMapping(value = "searchDepByInstitution",method={ RequestMethod.GET } )
    public Object searchDepByInstitution(int inst_id) throws Exception{
        List rs = eventService.queryDepByInstitution(inst_id);
        return HttpResult.sucess(rs);
    }
    @ApiOperation(value="根据部门ID与角色ID查询用户", notes="根据部门ID与角色ID查询用户")
    @RequestMapping(value = "searchUserByDepIdAndRole",method={ RequestMethod.POST } )
    public Object searchUserByDepIdAndRole ( Integer dep_id, Integer role ,int page , int size) throws Exception{
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        List<UserInfo> list = userInfo.findAllByDepIdAndRole( dep_id , role , pageable );
        return HttpResult.sucess(list);
    }
    @RequiresRoles("1")
    @ApiOperation(value="查询失效用户", notes="查询失效用户")
    @RequestMapping(value = "searchInvalidUser",method={ RequestMethod.GET } )
    public Object searchInvalidUser() throws Exception{
        return  HttpResult.sucess( userInfo.findAllInvalidUser() );
    }

    @ApiOperation(value="查询用户登录IP", notes="查询用户登录IP")
    @RequestMapping(value = "searchUserIp",method={ RequestMethod.GET } )
    public Object searchUserIp(int user_id,int page,int size) throws Exception {
        return  HttpResult.sucess( userInfo.searchUserLoginIp(user_id,page,size) );
    }
    @ApiOperation(value="根据eid查询群聊", notes="根据eid查询群聊")
    @RequestMapping(value = "searchByEidGroupMessge",method={ RequestMethod.GET } )
    public Object searchByEidGroupMessge(int eid ,int pigeNo,int pigeSize){
        return HttpResult.sucess( eventService.queryByEidGroupMessge(eid,pigeNo,pigeSize));
    }
    /**
     * 文件上传具体实现方法;
     * @param file
     * @return
     */
    @RequestMapping(value="/upload",method={ RequestMethod.POST })
    @ResponseBody
    public Object handleFileUpload(@RequestParam("file")MultipartFile file){
        if( !file.isEmpty() ){
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return HttpResult.error( HttpState.NOT_EMPTY.code() ,"上传失败,"+e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                return HttpResult.error( HttpState.NOT_EMPTY.code() ,"上传失败,"+e.getMessage());
            }
            return HttpResult.sucess("上传成功");
        }else{
            return HttpResult.error( HttpState.NOT_EMPTY.code() ,"上传失败，因为文件是空的.");
        }
    }
    /* 多文件具体上传时间，主要是使用了MultipartHttpServletRequest和MultipartFile
     * @param request
     * @return
    */
    @RequestMapping(value="/uploads", method= RequestMethod.POST)
    @ResponseBody
    public Object handleFileUpload(HttpServletRequest request){
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i =0; i< files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream =  null;
                    return HttpResult.error( HttpState.NOT_EMPTY.code() ,"["+file.getName()+"]上传失败,"+e.getMessage());
                }
            } else {
                return HttpResult.error( HttpState.NOT_EMPTY.code() ,"["+file.getName()+"]上传失败,文件不能为空");
            }
        }
        return HttpResult.sucess("上传成功");
    }
    /**
     * 发送邮件
     */
/*    @ApiOperation(value="发送邮件", notes="发送邮件")
    @RequestMapping(value="/send_email", method= RequestMethod.POST)
    @ResponseBody
    public Object sendSimpleEmail(String title,String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1353208670@qq.com");//发送者.
        message.setTo("330390619@qq.com");//接收者.
        message.setSubject(title);//邮件主题.
        message.setText(content);//邮件内容.
        mailSender.send(message);//发送邮件
        return HttpResult.sucess();
    }*/
    /**
     * 定时任务测试
     *
     */
    @Configuration
    @EnableScheduling
    public class SchedulingConfig {
        @Scheduled(cron = "0/60 * * * * ?") // 每60秒执行一次
        public void scheduler() {
            System.out.println(">>>>>>>>> "+ TimeUtil.sdf_1.format(new Date()));
        }
    }
}
